var connect_ip = connect_ip;
var connect_port = connect_port;
var db_instance_ha_type = db_instance_ha_type;
var connect_user = connect_user;
var console_panel , object_panel;
var user_token = user_token;
var isShowSessionOut = 0;
var rootUrl = getRoot();

var gLogin = {};
var loginOut = function() {
    Ext.MessageBox.confirm(message.confirm, message.exit, function(btnid){
        if(btnid === 'yes') {
            window.onbeforeunload = null;
            storeTabs();
            window.location = '/logout.do?token=' + user_token;
        }
    });
};

var ecsLoginOut = function() {
    Ext.MessageBox.confirm(message.confirm, message.exit, function(btnid){
        if(btnid === 'yes') {
            window.onbeforeunload = null;
            storeTabs();
            window.location = '/ecsInstancelogout.do?token=' + user_token;
        }
    });
};
//菜单栏跳转链接
function optionByDataKey(dataKey) {
    switch (dataKey) {
        case "table" :
            console_panel.addUrlPanel(rootUrl+'/dataManage/createNewTablePage', '', 'table', 'create');
            break;
        case "procedure":
            console_panel.addUrlPanel(rootUrl+'/dataManage/getProcedurePage', '', 'proc', 'create',null,null,null,'PROCEDURE');
            break;
        case "function":
            console_panel.addUrlPanel(rootUrl +'/dataManage/function/function-page', '', 'func', 'create',null,null,null,'FUNCTION');
            break;
        case "view":
            console_panel.addUrlPanel(rootUrl+'/dataManage/view/createViewBase', '', 'view', 'create');
            break;
        case "trigger":
            console_panel.addUrlPanel(rootUrl+'/dataManage/trigger/createTrigger', '', 'trigger', 'create',null,null,null,'TRIGGER');
            break;
        case "event":
            console_panel.addUrlPanel(rootUrl+'/dataManage/event/createEvent', '', 'event', 'create',null,null,null,'EVENT');
            break;

        case "diagnosis":
            console_panel.addUrlPanel('/instance/diagnosis.do', diagnosticReport, 'diagnosis', 'instance');
            break;
        case "tunninglist":console_panel.addUrlPanel('/tunning/tunningListPage.do' , optimizationList, 'tunninglist' , 'instance'); 
        	break;
        case "orzdba":
            console_panel.addUrlPanel('/instance/orzdba.do', realTimeCapability, 'orzdba', 'instance');
            break;
        case "processlist":
            console_panel.addUrlPanel('/instance/showprocesslist.do', instanceSession, 'showprocesslist', 'instance');
            break;
        case "locks":
            console_panel.addUrlPanel('/instance/locks.do', lockWait, 'locks', 'instance');
            break;
        case "tableSummaryPage":
            console_panel.addUrlPanel('/instance/tablesummary/gettablesummarypage.do', tableDataStatistics, 'tablesummary', 'instance');
            break;
        case "oneKeyClean":
            console_panel.addUrlPanel('/instance/oneKeyClean.do', keyEmpty, 'oneKeyClean', 'instance');
            break;

        case "sqlWindow":
            console_panel.addTmpURLPanel(rootUrl+'/websql/gmwebsql/multiSqlWindow', sqlWindow, 'sqlWindow');
            break;
        case "sqlCommand":
            console_panel.addTmpURLPanel('/data/sqlCommand.do', commandWindow, 'sqlCommand');
            break;
        case "export_mp":
            console_panel.addUrlPanel(rootUrl+'/dataManage/exportBaseView', 'export_base_view', 'export', 'export');
            break;
        case "import_mp":
            console_panel.addUrlPanel('/data/import/importBaseView.do', 'import_base_view', 'import', 'import');
            break;

        case "manage_db":
            console_panel.addUrlPanel('/management/database/toManagePage.do', databaseManage, 'manage_db', 'manage_db');
            break;
        case "manage_user":
            console_panel.addUrlPanel('/management/user/toUserManagePage.do', userManage, 'manage_user', 'manage_user');
            break;
        case "manage_binlog":
            console_panel.addUrlPanel('/management/binlog/toBinlogManagePage.do', logManage, "manage_binlog", 'manage_binlog');
            break;
        case "manage_erchart":
            console_panel.addUrlPanel('/management/erchart/showErcharts.do', menu.ERFigure, "manage_erchart", 'manage_erchart');
            break;

        case "grant_user_instance":
            console_panel.addUrlPanel("/grantInstance/toGrantPage.do", "云用户授权", "grant_user_instance", 'grant');
            break;
        case "grant_source_instance":
            console_panel.addUrlPanel("/grantInstance/to-grant-source.do" , "访问来源授权" , "grant_source_instance" , "grant");
            break;
        case "more_diagno":
        	console_panel.addUrlPanel("/system/moreDiagno.do", mainMore.diagno, "diagno", "more");
        	break;
        case "more_status":
        	console_panel.addUrlPanel("/system/moreStatus.do", mainMore.status, "status", "more");
        	break;
        case "more_grant":
        	console_panel.addUrlPanel("/system/moreGrant.do", mainMore.grant, "grant", "more");
        	break;
    }
}
var initPageHeader= function () {
    //用户的初始化处理
    function initUserCase(){
        var username= Ext.get("userName");
        var userCaseAction = username.child(".userCaseAction");
        if(username) {
            var fullName="";
            var shortName=Ext.get("instance_area").getHTML();
            //修改为鼠标滑动的效果
            username.hover(function(){
                //over func
                if(userCaseAction) {
                    userCaseAction.show();
                }
                fullName=Ext.get("instance_area").getAttribute("data-fullName")||Ext.get("instance_area").getHTML();
                shortName= Ext.get("instance_area").getHTML();
                Ext.get("instance_area").setHTML(fullName);

            },function(){
                //out func
                Ext.get("instance_area").setHTML(shortName);
                if(userCaseAction) {
                    userCaseAction.hide();
                }
            });
        }
    }
    initUserCase();

    //菜单列表的事件触发初始化
    var menuList=Ext.select(".menus .list");
    Ext.Array.each(menuList.elements,function(dd,index){
        var d= Ext.get(dd);
        var menu=d.child(".detail-menu");
        var bindOne= d.down("input.bindMenu");
        //修改为鼠标滑动的效果
        d.hover(function(){
            if(!d.hasCls("mover")){
                d.addCls("mover");
                menu.show(0);
            }

        },function(){
            if(d.hasCls("mover")){
                d.removeCls("mover");
                menu.hide(0);
            }
        });
    });

    var lis=Ext.get("main_header_info_bar").select(".js-console");
    Ext.Array.each(lis.elements,function(one,index){

        var tep=Ext.get(one);
        tep.on('click',function(evt){

            var dataKey = Ext.get(one).getAttribute("data-key");
            if(dataKey) {
                optionByDataKey(dataKey);
            }
            Ext.select(".detail-menu").hide(200);
        });
    });
};

var sessionOutCallBack = function (htmlContent) {
    if (isShowSessionOut > 0) {
        return;
    }
    isShowSessionOut = 1;
    var win = new IDB.Window({
        title: message.info,
        height: 110,
        width: 400,
        html: htmlContent,
        buttons: [
            {
                text: message.button.login, handler: function () {
                    storeTabs();
                    window.onbeforeunload = null;
                    window.location = rootUrl;
                }
            },
            {
                text: message.button.cancel, handler: function () {
                    win.close()
                }
            }
        ]
    });
    win.on('beforedestroy', function () {
        isShowSessionOut = 0;
    });
};
var createVerifyCodePanel = function () {
    var verifycodepanel = Ext.create("Ext.panel.Panel", {
        border: false,
        id: 'reconn_verifycode_panel',
        style: 'margin: 6px 0',
        layout: 'column',
        defaults: {
            autoFitErrors: false,//自动调整错误提示时候的宽度
            labelSeparator: ' : ',
            labelWidth: 80,
            allowBlank: false,
            labelAlign: 'right',
            xtype: 'textfield',
            msgTarget: 'side'
        }
    });

    var txt = Ext.create("Ext.form.field.Text", {
        fieldLabel: verifyCode.title,
        name: 'verifycode',
        allowBlank: false,
        blankText: verifyCode.notEmpty,
        labelWidth: 80,
        width: 150,
        labelAlign: 'right',
        listeners: {
            specialkey: function (field, e) {
                if (e.getKey() == Ext.EventObject.ENTER) {
                    gLogin.reconn();
                }
            }
        }

    });

    verifycodepanel.add(txt);
    var img = Ext.create('Ext.Img', {
        id: 'reconn_verifycode_img',
        src: "/getverifycode.do?r=" + Math.random(),
        style: 'height:21px; width: 100px; padding: 0px 0px 0px 20px; vertical-align: middle',
        listeners: {
            el: {
                click: function () {
                    img.setSrc("/getverifycode.do?r=" + Math.random());
                }
            }
        },
        renderTo: Ext.getBody()
    });

    verifycodepanel.add(img);
    var refreshbtn = Ext.create('Ext.Button', {
        text: verifyCode.refresh,
        style: 'width:80px; margin: 0 20px ',
        renderTo: Ext.getBody(),
        handler: function () {
            img.setSrc("/getverifycode.do?r=" + Math.random());
        }
    });
    verifycodepanel.add(refreshbtn);

    var formPanel = Ext.ComponentQuery.query("#reconnformpanel")[0];
    formPanel.insert(5 , verifycodepanel);
};

var checkVerifyCode = function () {
    var win = Ext.ComponentQuery.query("#reconnpopupwin")[0];

    win.setHeight(220);
    var theverifycodepanel = Ext.ComponentQuery.query('#reconn_verifycode_panel');
    if (theverifycodepanel && theverifycodepanel.length > 0) {
        theverifycodepanel = theverifycodepanel[0];

        var verifycodeimg = Ext.ComponentQuery.query('#reconn_verifycode_img')[0];
        verifycodeimg.setSrc("/getverifycode.do?r=" + Math.random());
    }
    else {
        createVerifyCodePanel();
    }
};

var buildIpPortItems = function (json , aloneLogin) {
    var items = [{
        xtype:'hidden',
        name:'ip'
    },{
        xtype:'hidden',
        name:'port'
    }];
    var specialKeyCallBack = function(field , e) {
        if (e.getKey() == Ext.EventObject.ENTER) {
            gLogin.reconn();
        }
    };
    if (aloneLogin) {
        items.push({
            xtype:'hidden',name:'dbType',value:'MySQL'
        },{
             fieldLabel: login.ipPort.title,
             name: 'connect',
             blankText: login.ipPort.notEmpty,
             listeners: {specialkey: specialKeyCallBack}
        });
    }else {
        var dataArray = [];
        Ext.each(json.connlist , function(row , i) {
            dataArray[i] = row;
            dataArray[i]['instance'] = row['domain'] + ":" + row['port'];
        });
        var store = Ext.create('Ext.data.Store', {
            fields: ['domain', 'port' , 'instance' , 'dbType'],
            data: dataArray
        });
        items.push({
            xtype:'combo',
            fieldLabel: login.ipPort.title,
            labelAlign: 'right',
            inputId: 'connect',
            store: store,
            queryMode: 'local',
            displayField: 'instance',
            valueField: 'instance',
            matchFieldWidth: true,
            listeners: {
                change: function (thiz, newValue, oldValue, eOpts) {
                    var record = thiz.findRecord(thiz.valueField || thiz.displayField, newValue);
                    var index = thiz.store.indexOf(record);
                }
            }
        });
    }
    items.push({
        fieldLabel: login.userName.title,
        name: 'userName',
        blankText: login.userName.notEmpty,
        listeners: {
            specialkey: specialKeyCallBack
        }
    });
    items.push({
        fieldLabel: login.password.title,
        inputType: 'password',
        name: 'password',
        id: 'reconnectpassword',
        blankText: login.password.notEmpty,
        listeners: {
            specialkey: specialKeyCallBack
        }
    });
    items.push({
        xtype:'checkboxfield',
        name:'remember',
        inputValue:'true',
        margin:"0 0 0 26",
        boxLabel:login.password.remember
    });
    items.push({
        name:'clientToken',
        xtype:'hidden'
    });
    return items;
};

gLogin.reconn = function () {
    var form = gLogin.formPanel;
    var connect = form.getForm().findField("connect");
    if(connect.getValue()) {
        var v = connect.getValue();
        if(v.indexOf(":") == -1) {
            return $.message.warning(login.ipPort.format);
        }
        var connectArray =  v.split(":");
        if(connectArray.length != 2) {
            return $.message.warning(login.ipPort.format);
        }
        var ip = connectArray[0];
        var port = connectArray[1];
        if(isNaN(port)) {
            return $.message.warning(login.ipPort.port);
        }
        form.getForm().findField("ip").setValue(ip);
        form.getForm().findField("port").setValue(port);
    }
    var loginURL = "/dologin.do?reconnect=true&onlyUrl=true";
    if (gLogin.formPanel.isValid()) {
        gLogin.formPanel.submit({
            url: loginURL,
            onlyUrl: true,
            waitMsg: login.logging,
            submitCallBack: function (panel, response, status) {
                var json = response.result;
                if (json.success) {
                    user_token = json.root.token;
                    loginSuccess();
                    gLogin.loginformwin.close();
                } else {
                    $.message.error(response.result.root.errmsg);
                    var reconnfailedcount = response.result.root.failedcount;
                    if (reconnfailedcount >= 3) {
                        checkVerifyCode();
                    }
                }
            }
        });
    }
};

var SimpleMap = function() {
    var object = {};
    var prefix = "k_";
    var simpleObject = "$$$";
    this.put = function(key , value) {
        object[prefix + key] = value;
    };
    this.putSimpleKey = function(key) {
        object[prefix + key] = simpleObject;
    };
    this.get = function(key) {
        return object[prefix + key];
    };
    this.getKeys = function() {
        var array = [];
        for(var p in object) {
            array.push(p.substring(prefix.length));
        }
        array.sort();
        return array;
    };
};
var getLoginFormWindow = function (json) {
    Ext.regModel('login_data_mode', {
        fields: ['ip' , 'port' , 'userName' , 'connect']
    });
    var aloneLogin = ((json['allowStandaloneLogin'] && json['defaultStandaloneLogin']));
    var instanceItems = buildIpPortItems(json , aloneLogin);

    var baseWidth = 520;
    gLogin.formPanel = new IDB.FormPanel({
        border: true,
        id: 'reconnformpanel',
        defaults: {
            width: baseWidth - 60,
            style: 'margin: 6px 0'
        },
        items: instanceItems,
        buttons: [
            {
                text: message.button.yes,
                handler: function () {
                    gLogin.reconn();
                }
            },
            {
                text: message.button.no, 
                handler: function () {
                	win.close();
                }
            }
        ]
    });
    var record = Ext.ModelMgr.create({ip: connect_ip, port: connect_port,connect:(connect_ip + ":" + connect_port), userName: connect_user}, 'login_data_mode');
    gLogin.formPanel.loadRecord(record);
    var win = new IDB.Window({
        width: 520, height: 200, title: login.reconnect,
        id: 'reconnpopupwin',
        items: [gLogin.formPanel]
    });
    if(!aloneLogin && json['userRememberLogin'] && json['userRememberLogin'].length > 0) {
        var form = gLogin.formPanel.getForm();
        var instanceF = form.findField("connect");
        var userF = form.findField("userName");
        var passwordF = form.findField("password");
        var rememberF = form.findField("remember");
        var clientTokenF = form.findField("clientToken");
        var default_password_background =  "$$idb_password_by_background$$";
        var rememberMap = new SimpleMap();
        var userRememberLogin = json['userRememberLogin'];
        for(var i = 0 ; i < userRememberLogin.length ; i++) {
            var row = userRememberLogin[i];
            var instanceMap = rememberMap.get(row['instanceName']);
            if(!instanceMap) {
                instanceMap = new SimpleMap();
                rememberMap.put(row['instanceName'] , instanceMap);
            }
            instanceMap.putSimpleKey(row['dbUserName']);
        }
        var connectionMap = rememberMap.get(record.get("connect"));
        if(connectionMap && connectionMap.get(record.get("userName"))) {
            passwordF.setValue(default_password_background);
            rememberF.setValue(true);
            clientTokenF.setValue(getLocalStorage(local_storage_key_name));
        }
        var preInstanceName = record.get("connect");
        var resetPass = function() {
            passwordF.setValue('');
            rememberF.setValue(false);
        };
        var resetAll = function() {
            userF.setValue('');
            resetPass();
        };
        instanceF.on('select'  ,function() {
            if(preInstanceName != instanceF.getValue()) {
                preInstanceName = instanceF.getValue();
                var connectionMap = rememberMap.get(preInstanceName);
                if(connectionMap) {
                    var keys = connectionMap.getKeys();
                    if(keys && keys.length > 0) {
                        userF.setValue(keys[0]);
                        passwordF.setValue(default_password_background);
                        rememberF.setValue(true);
                        clientTokenF.setValue(getLocalStorage(local_storage_key_name));
                    }else {
                        resetAll();
                    }
                }else {
                    resetAll();
                }
            }
        });
        userF.on('change' , function() {
            if(instanceF.getValue() && userF.getValue()) {
                var connectionMap = rememberMap.get(preInstanceName);
                if(connectionMap && connectionMap.get(Ext.String.trim(userF.getValue()))) {
                    passwordF.setValue(default_password_background);
                    rememberF.setValue(true);
                }else {
                    resetPass();
                }
            }else {
                resetPass();
            }
        });
    }
    if (json.failedcount && (json.failedcount >= 3)) {
        checkVerifyCode();
    }

    return win;
};
var loginSuccess = function () {
    ajax({
        url: '/system/findLoginInfo.do?token=' + getUserToken(),
        onlyUrl:true,
        success: function (response) {
            var json = jsonDecode(response.responseText);
            if (json.success) {
                var root = json.root;
                if(connect_ip != root.ip || connect_port != root.port || connect_user != root.userName) {
                    connect_ip = root.ip;
                    connect_port = root.port;
                    connect_user = root.userName;
                    db_charset = root.db_charset;
                    //storeDBVersion();//存储dbVersion
                    global_main_panel.resetTitle();
                    global_main_panel.refreshComponents();
                    Ext.get('welcome_page_id').dom.src = getRoot()+"/websql/gmwebsql/welcome";
                    console_panel.closeNotSQLPanel();
                }
            }
        }
    });
};
var global_main_panel;
var createWorkspacePanel = function () {
    initStoreTabs();
    var showConnectWindow = function () {
        getLoginFormWindow();
    };
    var showInstanceWindow = function () {
        var htmlCode = getFrameHtml('/instance/instanceBase.do');
        var win = new IDB.Window({
            width: 1024, height: 560, closable: true,
            maximizable: true,
            title: workspace.instance.title + ':【' + connect_ip + ":" + connect_port + "】 " + workspace.instance.information,
            items: [
                {
                    border: false, scripts: true, autoScroll: true,
                    discardUrl: true, nocache: true, timeout: 9000, scope: this, html: htmlCode
                }
            ]
        });
    };
    global_main_panel = new Ext.Panel({
        //frame: true,
        border: 0,
        layout: 'border',
        width:"auto",
        defaults: {
            split: true,
            collapsible: true
        },
        items: [
            createHeaderPanel(),
            object_panel = createObjectSpacePanel(),
            console_panel = createWorkspaceCenterPanel()
        ],
        resetTitle: function () {
            var instHATypeSpan = document.getElementById("instHAType");
            if (instHATypeSpan && db_instance_ha_type) {
                instHATypeSpan.innerHTML = db_instance_ha_type;
            }
            var shortShow="";
            var len=connect_ip.length;
            if(connect_ip.length>
            23){
                shortShow += connect_ip.substring(0,15);
                shortShow += "...";
                shortShow += connect_ip.substring(len-5,len);
                shortShow += ":"+ connect_port;
            }else{
                shortShow += connect_ip+":"+connect_port;
            }
            var instance = document.getElementById("instance_area");
            if(instance) {
                instance.innerHTML=shortShow;
                var dataN = document.createAttribute("data-fullName");
                if(dataN) {
                    dataN.nodeValue = connect_ip+":"+connect_port;
                    instance.attributes.setNamedItem(dataN);
                }
            }
        },
        refreshComponents: function () {
            object_panel.refreshDatabases();
        }
    });
    global_main_panel.resetTitle();
    return global_main_panel;
};
/*
 *   header panel  页面头部
 **/
var createHeaderPanel = function () {
    return Ext.Panel({
        region: 'north',
        contentEl: 'header_div',
        border: false,
        split: false,
        collapsible: false,
        baseCls:"fixHeightBug",
        bodyStyle: {
            height:"300px"
        }
    })
};

var resetTabTitle = function(preId,newTitle) {
	console_panel.resetTabTitle(preId , newTitle);
};
var init_store_tabs = {};
var initStoreTabs = function() {
    init_store_tabs = jsonDecode(
        SimpleStorageUtils.getByDefault("__DMS_INSTANCE_" + connect_ip + ":" + connect_port + "@" + connect_user , "{}")
    );
};
var isMetadataDB = function(dbName) {
    return dbName == 'mysql' || dbName == 'information_schema' || dbName == 'performance_schema' || dbName == 'sys';
};
var createObjectSpacePanel = function () {

    var tablePanel , viewPanel, progObjPanel;
    var workSpacePanel = new IDB.TabPanel({
        collapsible:false,
        items: []
    });
    var nowDBName = init_store_tabs['dbName'] || null , oldDBName = null, initedObjects = false;


    var onlyRefresh = function () {
        refreshTabPanel();
        refreshViewPanel();
        //refreshProgObjPanel();
    };

    var refreshEvery = function () {
        if (nowDBName && oldDBName != nowDBName) {
            oldDBName = nowDBName;//参数中携带dbName
            if (!tablePanel) {
                Ext.getBody().unmask();
                tablePanel = createTablePanel(nowDBName);
                workSpacePanel.add(tablePanel);
                workSpacePanel.setActiveTab(0);
            } else {
                refreshTabPanel();
            }
            if (!viewPanel) {
                viewPanel = createViewPanel(nowDBName);
                workSpacePanel.add(viewPanel);
            } else {
                refreshViewPanel();
            }


            if (!progObjPanel) {
                progObjPanel = createProgObjPanel(nowDBName);
                workSpacePanel.add(progObjPanel);
            }
            else {
                refreshProgObjPanel();
            }
        }else {
            Ext.getBody().unmask();
        }
    };

    var refreshTabPanel = function () {
        tablePanel.refreshByDBName(nowDBName);
    };

    var refreshViewPanel = function () {
        viewPanel.refreshByDBName(nowDBName);
    };


    var refreshProgObjPanel = function () {
        progObjPanel.refreshByDBName(nowDBName);
    };

    var dbCommon = null , forceSelectFirst = (nowDBName == null);
    var refreshStore = function () {
        Ext.getBody().mask(objectSpace.refeshing);
        dbCommon.store.load();
    };
    return createWrapperPanel(workSpacePanel, {
        region: 'west', width: 220,
        title: objectSpace.title,
        split:true,
        header:false,
        collapsible:false,
        refreshDatabases: function () {
            forceSelectFirst = true;//切换数据库实例时才会调用
            dbCommon.store.load();
        },
        tbar: [
            dbCommon = new IDB.CommonBox({
                width: 165,
                loadSelectFirst: true,
                url: rootUrl + '/websql/getDataBase?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal,
                loadSelect:function(combo) {
                    var checkRow = (forceSelectFirst ? null : nowDBName);
                    forceSelectFirst = false;
                    combo.store.each(function(record) {
                        var data = record.get('data');
                        if(data == ""){
                        	Ext.Msg.alert('提示', '您没有任何权限！请联系管理员。');
                        	return;
                        }
                        if(!checkRow && !isMetadataDB(data)) {
                            checkRow = data;
                        }
                    });
                    if(checkRow) {
                        combo.setValue(checkRow);
                    }else {
                        combo.selectFirst();
                    }
                    if(nowDBName) {
                        nowDBName = combo.getValue();
                    }
                },
                loadCallBack: function (combo) {
                    if (initedObjects) {
                        if (combo.store.find('data', nowDBName) != -1) {//切换实例或库被改
                            combo.setValue(nowDBName);
                        } else {
                            nowDBName = combo.getValue();
                        }
                        onlyRefresh();
                    } else {
                        nowDBName = combo.getValue();
                        refreshEvery();
                        initedObjects = true;
                    }
                },
                selectCallBack: function (combo) {
                    nowDBName = combo.getValue();
                    refreshEvery();
                }
            }),
            {
                iconCls: 'fa fa-refresh', handler: function () {
                    setTimeout(refreshStore, 100);
                }
            }
        ],
        getNowDBName: function () {
            return nowDBName || '';
        },
        refreshone: function (objecttype) {
            if (objecttype === objectTypeMap.table) {
                refreshTabPanel();
            }else if (objecttype === objectTypeMap.view) {
                refreshViewPanel();
            }else if (objecttype === objectTypeMap.progobjs) {
                refreshProgObjPanel();
            }
        },
        refreshTabPanel: function () {
            tablePanel.refreshByDBName(nowDBName);
        },
        refreshViewPanel: function () {
            viewPanel.refreshByDBName(nowDBName);
        },
        collapseCombo: function () {
            dbCommon.collapse();
            Ext.each(PUBLIC_RIGHT_MENUS, function (rightMenu) {
                rightMenu.hide();
            });
        },
        refreshTableChild:function(node) {
            tablePanel.refreshNodeCallBack(node);
        }
    });
};
var executeSQLWithCallback = function(_script , dbName , fn , otherName , maskWin ,params,parentWindow,win) {
    params.script = _script;
    var url = getRoot() + '/dataManage/executeScript';
    var d = new Ext.util.DelayedTask(function() {
        ajax({
            url: url,
            timeout:3600000 * 12,
            params:params,
            success: function (resp) {
                unMaskBodyOrWin(maskWin);
                var json = jsonDecode(resp.responseText);
                if (json.success) {
                	if(isLocal == 'isLocal'){
                		$.feedbackMessage({type: 'success',message: json.root,showTime:5000});
             	   }else{
						$.feedbackMessage({type: 'success',message: json.root,showTime:5000});
             	   }
                	win.close();
                	parentWindow.close();
                }else {
                    $.message.error(json.root);
                }
            },
            failure: function (resp) {
                unMaskBodyOrWin(maskWin);
                $.message.error('执行出错，通常是SQL响应时间太长！');
            }
        });
    });
    d.delay(100);
};
var onlyExecuteSQL = function (content, panel, nowDBName, objectName, objectType, successMsg,records) {
    Ext.getBody().mask(message.mask.change);
    ajax({
        url: getRoot() + '/dataManage/table/executeScriptByMainPanel',
        params: {
        	script: content, 
        	dbName: nowDBName,
        	tableName:objectName,
        	databaseType:base_type,
        	dataSourceId:dataSource_id,
        	dataSource:data_source,
        	databaseId:dataBase_id,
        	isLocal:isLocal
        },
        success: function (resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            json = json.responseText;
            if (json.success) {
            	if(records){
            		for(var j=0;j<records.length;j++){
            			records[j].set('status' , 'success');
                    }
            	}
            	$.message.success(json.root,6000);
            } else {
            	if(json.failure){
            		if(records){
                		for(var j=0;j<records.length;j++){
                			records[j].set('status' , 'error');
                        }
                	}
            		$.message.error(json.root);
            	}
            }
        },
        failure: function (resp) {
        	if(records){
        		for(var j=0;j<records.length;j++){
        			records[j].set('status' , 'error');
                }
        	}
            Ext.getBody().unmask();
            $.message.error("执行出错，通常是SQL响应时间太长！");
        }
    });
};
var createTablePanel = function (nowDbName) {
	
    var treeStore = new IDB.TreeStore({
        //autoLoad: false,
        dbName: nowDbName,
        fields:['id' , 'text' , 'expanded' , 'leaf' , 'iconCls' , 'children', 'treeType' , 'tableName' , 'realName' , 'realText'],
        url: rootUrl + '/websql/getAllDbTables?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal
    });
    var tmpRecord = null , expandNodeType = null , expandNodeName = null;
    treeStore.on('load', function () {
        tree.setLoading(false);
    });
    treeStore.on('beforeload' , function(store , operation) {
        if(operation.params) {
            if(!operation.params['type']) {
                operation.params['type'] = expandNodeType;
            }
            if(!operation.params['name']) {
                operation.params['name'] = expandNodeName;
            }
        }
    });
    var resetExpanded = function() {
        expandNodeType = null;
        expandNodeName = null;
    };

    var tableControlCallBack = function(start,end) {
        if (tmpRecord) {
            var tabName = tmpRecord.get('text');
            var sql = start + ' TABLE `' + tabName.replaceAll("`" , "``") + "`";
            if(end) {
                sql += " " + end;
            }
            Ext.Msg.confirm(message.info , left.table.operation.tableMaintenance.confirmPre + sql + left.table.operation.tableMaintenance.confirmAfter , function(v) {
                if(v == 'yes') {
                    executeSQLWithCallback(sql , tmpDBName);
                }
            });
        }
    };
    var isLimitExport = (limitExport == "PRD");
    var tableRightMenu = new Ext.menu.Menu({
        items: [
            {
                text: left.table.operation.SQLoperation.title, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    console_panel.addUrlPanel(rootUrl+'/websql/gmwebsql/multiSqlWindow', tabName, 'sqlWindow', 'query' , null , getSQLWindowParamsStr("sqlWindow" , ""));
                }
            }
            },{
                text: left.table.operation.openTable, handler: function () {
                    if (tmpRecord) {
                        var tabName = tmpRecord.get('text');
                        console_panel.addUrlPanel(rootUrl+'/dataManage/queryTable', tabName, 'query_table', 'query_table');
                    }
                }
            },{
                text: left.table.operation.bi, hidden: !biApiStart, handler: function () {
                    if (tmpRecord) {
                        var tabName = tmpRecord.get('text');
                        window.open("/mysql/biAnalysisTable.do?dbName="
                            + encodeURIComponent(object_panel.getNowDBName())
                            + "&tableName=" + encodeURIComponent(tabName)
                            + "&token=" + user_token);
                    }

                }
            },{
                text:left.table.operation.dataTrend,
                hidden: rdsFlag == "null",
                menu:[
                    {
                        text: left.table.operation.tableDataTrend, handler:function() {
                        if (tmpRecord) {
                            var tabName = tmpRecord.get('text');
                            console_panel.addUrlPanel("/instance/tableDataTrend.do?dbName="
                                + encodeURIComponent(object_panel.getNowDBName())
                                + "&tableName=" + encodeURIComponent(tabName)
                                + "&token=" + user_token,'表变化:'+tabName,'dateStatistics' ,'instance');

                        }
                    }
                    },
                    {
                        text: left.table.operation.dbDataTrend, handler:function() {
                        if (tmpRecord) {
                            var tabName = tmpRecord.get('text');
                            console_panel.addUrlPanel("/instance/dbDataTrend.do?dbName="
                                + encodeURIComponent(object_panel.getNowDBName())
                                + "&tableName=" + encodeURIComponent(tabName)
                                + "&token=" + user_token,'库变化:'+tabName,'dateStatistics' ,'instance');

                        }
                    }
                    }
                ]
            },'-',
            {
                text: left.table.operation.newTable, handler: function () {
                	if (tmpRecord) {
                         console_panel.addUrlPanel(rootUrl+'/dataManage/createNewTablePage', '', 'table', 'create');
                     }
            }
            },
            {
                text: left.table.operation.editStructure, handler: function () {
                if (tmpRecord) {
                    console_panel.addUrlPanel(rootUrl+'/dataManage/createNewTablePage', tmpRecord.get('text'), 'table', 'change');
                }
            }
            },{
                text:'表结构对比',
                hidden:!biApiStart,
                handler:function() {
                    console_panel.addUrlPanel("/structure/compare/to-compare-page.do?action=add", "表结构对比", "structure_compare", 'more');
                }
            },'-',
            {
                text: left.table.operation.dropTable.title, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    Ext.Msg.confirm(message.warning, left.table.operation.dropTable.confirmMsg + ' 【' + tabName + '】？', function (v) {
                        if (v == 'yes') {
                            onlyExecuteSQL('drop table ' +tmpDBName+'.'+tabName, tree, tmpDBName, tabName, 'table');
                        }
                    });
                }
            }
            },{
                text: left.table.operation.emptyTable.title, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    Ext.Msg.confirm(message.warning, left.table.operation.emptyTable.confirmMsg + ' 【' + tabName + '】？', function (v) {
                        if (v == 'yes') {
                            onlyExecuteSQL('truncate table ' + tabName, tree, tmpDBName, tmpRecord.get('text'), 'table', left.table.title + '【' + tabName + '】' + left.table.operation.emptyTable.callbackMsg + '!');
                        }
                    });
                }
            }
            },
            {
                text: left.table.operation.rename.title, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    var form = new IDB.FormPanel({
                        margin: '2 0 0 0',
                        items: [
                            {
                                xtype: 'textfield',
                                width: 460,
                                name: 'toName',
                                fieldLabel: left.table.operation.rename.confirmMsg,
                                labelWidth: 130,
                                value: tabName
                            }
                        ],
                        buttons: [
                            {
                                text: message.button.yes, handler: function () {
                                var toName = form.getForm().findField('toName').getValue();
                                if (!toName) {
                                    return $.message.warning(left.table.operation.rename.notNull);
                                }
                                if (toName == tabName) {
                                    return $.message.warning(left.table.operation.rename.notSame);
                                }
                                onlyExecuteSQL('rename table ' +tmpDBName+'.'+tabName+ " to " + toName, tree, tmpDBName, tmpRecord.get('text'), 'table');
                                win.close();
                            }
                            },
                            {
                                text: message.button.no, handler: function () {
                                win.close();
                            }
                            }
                        ]
                    });
                    var win = new IDB.Window({
                        title: left.table.operation.rename.confirmTitle + '：[' + tabName + "]", items: [form], width: 500, height: 110
                    });
                }
            }
            },
            {
                text: left.table.operation.similarCreation.title, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    var form = new IDB.FormPanel({
                        margin: '2 0 0 0',
                        items: [
                            {
                                xtype: 'textfield',
                                name: 'toName',
                                width: 460,
                                fieldLabel: left.table.operation.similarCreation.confirmMsg,
                                labelWidth: 130,
                                value: tabName
                            }
                        ],
                        buttons: [
                            {
                                text: message.button.yes, handler: function () {
                                var toName = form.getForm().findField('toName').getValue();
                                if (!toName) {
                                    return $.message.warning(left.table.operation.similarCreation.notNull);
                                }
                                if (toName == tabName) {
                                    return $.message.warning(left.table.operation.similarCreation.notSame);
                                }
                                onlyExecuteSQL('create table ' + toName + " like " +tmpDBName+ '.' +tabName, tree, tmpDBName, tmpRecord.get('text'), 'table');
                                win.close();
                            }
                            },
                            {
                                text: message.button.no, handler: function () {
                                win.close();
                            }
                            }
                        ]
                    });
                    var win = new IDB.Window({
                        title: left.table.operation.similarCreation.confirmPre + ': [' + tabName + '] ' + left.table.operation.similarCreation.confirmAfter, items: [form], width: 500, height: 110
                    });
                }
            }
            },{
                text: left.table.operation.batchOperation.title,menu:[{
                    text: left.table.operation.batchOperation.drop,handler:function() {
                        dropTables(tmpDBName , Ext.getCmp('likeTableName').getValue());
                    }
                },{
                    text: left.table.operation.batchOperation.more,
                    handler:function() {
                    	Ext.Msg.alert('提示' , '正在开发中，敬请期待！');
                    	return;
                        console_panel.addUrlPanel('/structure/table/tableList.do', '', '', 'tableBatchOptr',tmpDBName);
                    },
                    hidden:true
                }]
           },'-',
            {
                text: left.table.operation.templateSQL, handler: function () {
                if (tmpRecord) {
                    var tabName = tmpRecord.get('text');
                    Ext.getBody().mask(message.mask.load);
                    ajax({
                    	url:getRoot() + '/dataManage/table/getDBTableStructure',
                        params:{tableName:tabName,dbName:tmpDBName,baseType:base_type,dataBaseId:dataBase_id,dataSourceId:dataSource_id,dataSource:data_source,isLocal:isLocal},
                        success: function (resp) {
                            Ext.getBody().unmask();
                            var json = JSON.parse(resp.responseText);
                            json = json.responseText;
                            if (json.success) {
                                showTableTemplateSQL(json.root,base_type);
                            } else {
                                $.message.error(json.root);
                            }
                        },
                        failure: function () {
                            Ext.getBody().unmask();
                            $.message.error('执行出错，通常是SQL响应时间太长！');
                        }
                    });
                }
            }
            },
            {
                text: left.table.operation.tableMaintenance.title,
                menu:[{
                    text: left.table.operation.tableMaintenance.optimize,handler:function() {
                        tableControlCallBack('OPTIMIZE');
                    }
                },{
                    text: left.table.operation.tableMaintenance.check.title,menu:[{
                        text: left.table.operation.tableMaintenance.check.normal,handler:function() {
                            tableControlCallBack('CHECK');
                        }
                    },{
                        text: left.table.operation.tableMaintenance.check.quick,handler:function() {
                            tableControlCallBack('CHECK' , 'QUICK');
                        }
                    },{
                        text: left.table.operation.tableMaintenance.check.fast,handler:function() {
                            tableControlCallBack('CHECK' , 'FAST');
                        }
                    },{
                        text: left.table.operation.tableMaintenance.check.changed,handler:function() {
                            tableControlCallBack('CHECK' , 'CHANGED');
                        }
                    },{
                        text: left.table.operation.tableMaintenance.check.extended,handler:function() {
                            tableControlCallBack('CHECK' , 'EXTENDED');
                        }
                    }]
                },{
                    text: left.table.operation.tableMaintenance.repair.title,menu:[{
                        text: left.table.operation.tableMaintenance.repair.normal,handler:function() {
                            tableControlCallBack('REPAIR');
                        }
                    },{
                        text: left.table.operation.tableMaintenance.repair.quick,handler:function() {
                            tableControlCallBack('REPAIR' , "QUICK");
                        }
                    },{
                        text: left.table.operation.tableMaintenance.repair.extended,handler:function() {
                            tableControlCallBack('REPAIR' , "EXTENDED");
                        }
                    }]
                },{
                    text: left.table.operation.tableMaintenance.analyze,handler:function() {
                        tableControlCallBack('ANALYZE');
                    }
                }],
                hidden:true
            },'-',
            {
                text:'导出',
                hidden:isLimitExport,
                menu: [
                    {
                        text: left.table.operation.exportTable.title, 
                        hidden: isLimitExport, 
                        handler: function () {
                        if (limitExport == "PRD") {
                            return $.message.warning(left.table.operation.exportTable.limit);
                        	}
                        var result = console_panel.addUrlPanel(rootUrl+'/dataManage/exportBaseView', 'export_base_view', 'export', 'export', tmpDBName,
                            jsonToString({tableName: tmpRecord.get('text'), dbName: tmpDBName, exportType: 'table'}));
                        if (result && result.old) {
                            var iframe = document.getElementById(result.old + "_iframe");
                            iframe.contentWindow.addTableJob({tableName: tmpRecord.get('text'), dbName: tmpDBName, exportType: 'table'});
                        	}
                        }
                    },
                    {
                        text: left.table.operation.exportDatabase, 
                        hidden: true, 
                        handler: function () {
                        if (limitExport == "PRD") {
                            return $.message.warning(left.table.operation.exportTable.limit);
                        	}
                        var result = console_panel.addUrlPanel(rootUrl+'/dataManage/exportBaseView', 'export_base_view', 'export', 'export', tmpDBName,
                            jsonToString({exportType: 'db', dbName: tmpDBName}));
                        if (result && result.old) {
                            var iframe = document.getElementById(result.old + "_iframe");
                            iframe.contentWindow.addNewDBJob({exportType: 'db', dbName: tmpDBName});
                        	}
                        }
                    },{
                        text:'生成文档（Word、Excel、PDF）',
                        hidden:true,
                        menu:[{
                            text:'生成Word文档',handler:function() {
                                var url = "/mysql/dictionary/download-doc.do?nowDBName="
                                    + encodeURIComponent(tmpDBName) + "&token=" + user_token;
                                downLoadFileByURL(url);
                            }
                        },{
                            text:'生成Excel文档',
                            handler:function() {
                                var url = "/mysql/dictionary/download-xls.do?nowDBName="
                                    + encodeURIComponent(tmpDBName) + "&token=" + user_token;
                                downLoadFileByURL(url);
                            }
                        },{
                            text:'生成PDF文档',
                            handler:function() {
                                var url = "/mysql/dictionary/download-pdf.do?nowDBName="
                                    + encodeURIComponent(tmpDBName) + "&token=" + user_token;
                                downLoadFileByURL(url);
                            }
                        },{
                            text:'在线浏览',
                            handler:function() {
                                window.open('/mysql/dictionary/showdict.do?nowDBName=' + encodeURIComponent(tmpDBName) + "&token=" + user_token + "&panelKey=dictionary");
                            }
                        }]
                    },{
                        text: '导出建表DDL',
                        hidden:true,
                        handler:function() {
                            exportAllStructure(tmpDBName);
                        }
                    }
                ]
            },
            {
                text: left.table.operation.flush, 
                handler: function () {
                if (tmpDBName) {
                    tree.refreshByDBName(tmpDBName);
                	}
                }
            },
            {
                text: left.table.operation.object, handler: function () {
                	if (tmpRecord) {
                        var tabName = tmpRecord.get('text');
                        Ext.getBody().mask(message.mask.load);
                        ajax({
                        	url:getRoot() + '/dataManage/table/getDBTableStructure',
                            params:{tableName:tabName,dbName:tmpDBName,baseType:base_type,dataBaseId:dataBase_id,dataSourceId:dataSource_id,dataSource:data_source,isLocal:isLocal},
                            success: function (resp) {
                                Ext.getBody().unmask();
                                var json = JSON.parse(resp.responseText);
                                json = json.responseText;
                                if (json.success) {
                                	showTableObject(json.root);
                                } else {
                                    $.message.error(json.root);
                                }
                            },
                            failure: function () {
                                Ext.getBody().unmask();
                                $.message.error('执行出错，通常是SQL响应时间太长！');
                            }
                        });
                    }
                }
            }
        ]
    });
    var tableRightMenu2 = new Ext.menu.Menu({
        items: [
            {
                text: left.table.operation.newTable, handler: function () {
                	Ext.Msg.alert('提示' , '正在开发中，敬请期待！');
                	return;
//                    console_panel.addUrlPanel('/structure/table/tableBase.do', '', 'table', 'create');
                }
            },
            {
                text: left.table.operation.flush, handler: function () {
                    if (tmpDBName) {
                        tree.refreshByDBName(tmpDBName);
                    }
                }
            }
        ]
    });
    var nowRightMenuRecord = null , nowLeafRecord = null;
    var setNodeTextByChild = function(node) {
        var length = node.childNodes.length;
        node.set('text' , node.get('realText') + "（" + length + "）");
    };
    var refreshNowCallBack = function(node) {
        node = node || nowRightMenuRecord;
        expandNodeType = node.get('treeType');
        expandNodeName = node.get('tableName') || node.get('text');
        treeStore.load({
            node:node,
            callback:function() {
                setNodeTextByChild(node);
                node.expand();
            }
        });
    };
    var addColumnMenu =  {
        text: menu.column.add, handler:function() {
        	if(base_type == 'drds'){
        		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
            	return;
        	}else{
        		addNewColumn(tmpDBName ,nowRightMenuRecord , null,base_type);
        	}
        }
    };
    var columnGroupRightMenu = new Ext.menu.Menu({
        items:[
            addColumnMenu,{
                text: menu.refresh, 
                handler:function() {
                	refreshNowCallBack();
                	}
            	}
        ]
    });
    var columnRightMenu = new Ext.menu.Menu({
        items:[
            addColumnMenu,{
                text: menu.column.edit, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		addNewColumn(tmpDBName ,nowRightMenuRecord , nowLeafRecord.get('realName'),base_type);
                	}
                }
            },{
                text: menu.column.drop, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		deleteColumn(tmpDBName ,nowRightMenuRecord , nowLeafRecord.get('realName'),base_type);
                	}
                }
            },{
                text: menu.refresh, handler:function() {refreshNowCallBack();}
            }
        ]
    });
    var indexGroupMenu = new Ext.menu.Menu({
        items:[
            {
                text: menu.index.add, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		addTableIndex(tmpDBName , nowRightMenuRecord , null,base_type);
                	}
                }
            },{
                text: menu.refresh, handler:function() {refreshNowCallBack();}
            }
        ]
    });
    var indexMenu = new Ext.menu.Menu({
        items:[
            {
                text: menu.index.add, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		addTableIndex(tmpDBName , nowRightMenuRecord , null, now_db_type);
                	}
                }
            },{
                text: menu.index.edit, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		addTableIndex(tmpDBName , nowRightMenuRecord , nowLeafRecord.get('realName') , now_db_type);
                	}
                }
            },{
                text: menu.index.drop, handler:function() {
                	if(base_type == 'drds'){
                		Ext.Msg.alert('提示' , '不支持此DRDS数据源类型操作');
                    	return;
                	}else{
                		deleteIndex(tmpDBName , nowRightMenuRecord , nowLeafRecord.get('realName'),now_db_type);
                	}
                }
            },{
                text: menu.refresh, handler:function() {refreshNowCallBack();}
            }
        ]
    });
    PUBLIC_RIGHT_MENUS.push(tableRightMenu, tableRightMenu2 , columnGroupRightMenu , columnRightMenu , indexGroupMenu , indexMenu);
    var itemClickCallback = function(thiz , record , e) {
        var type = record.get('treeType');
        if(type == 'table')  {
            tmpRecord = record;
            tableRightMenu.showAt(e.getXY());
        }else if(type == 'column_group') {
            nowRightMenuRecord = record;
            columnGroupRightMenu.showAt(e.getXY());
        }else if(type == 'column') {
            nowLeafRecord = record;
            nowRightMenuRecord = record.parentNode;
            columnRightMenu.showAt(e.getXY());
        }else if(type == 'index_group') {
            nowRightMenuRecord = record;
            indexGroupMenu.showAt(e.getXY());
        }else if(type == 'index') {
            nowLeafRecord = record;
            nowRightMenuRecord = record.parentNode;
            indexMenu.showAt(e.getXY());
        }
    };
    var tmpDBName = nowDbName;
    var tree = new Ext.tree.Panel({
        store: treeStore,
        loadMask: true,
        emptyText: menu.click + '<a href="javascript:console_panel.addUrlPanel(\'getRoot()+/dataManage/createNewTablePage\', \'\', \'table\', \'create\');" style="font-weight: bold;color: #0000ff;">' + menu.here + '</a>' + menu.tableStart,
        title: left.table.title,
        rootVisible: false,
        refreshByDBName: function (dbName) {
            tmpDBName = treeStore.dbName = dbName;
            tree.setLoading(true);
            resetExpanded();
            var likeTableName = Ext.getCmp('likeTableName').getValue();
            treeStore.load({
                params:{likeTableName:likeTableName},
                callback: function () {
                    Ext.getBody().unmask();
                }
            });
        },
        refreshNodeCallBack:function(node) {
            refreshNowCallBack(node);
        },
        tbar:[{
            xtype:'textfield',
            id:'likeTableName',
            emptyText:left.table.emptyText,
            listeners:{
                specialkey:function(field , e) {
                    if(e.getKey() == e.ENTER) {
                        tree.refreshByDBName(tmpDBName);
                    }
                }
            }
        }],
        listeners: {
            itemclick: function (thiz, record, item, index, e) {
                itemClickCallback(thiz , record , e);
            },
            itemcontextmenu: function (thiz, record, item, index, e) {
                e.preventDefault();
                itemClickCallback(thiz , record , e);
            },
            containercontextmenu: function (thiz, e) {
                e.preventDefault();
                tableRightMenu2.showAt(e.getXY());
            },
            beforeitemexpand  : function(thiz , eOpts) {
                expandNodeType = thiz.get('treeType');
                expandNodeName = thiz.get('tableName') || thiz.get('text');
            },
            afteritemexpand:function(thiz) {
                var treeType = (thiz.get('treeType'));
                if(treeType == 'column_group' || treeType == 'index_group') {
                    setNodeTextByChild(thiz);
                }
            }
        }
    });
    return tree;
};
var exportAllStructure = function(dbName) {
    Ext.getBody().mask(message.mask.task);
    asynchronousAjax({
        url:'/data/export/exportDbStructure.do',
        retryUrl:'/data/export/monitorExportJob.do',
        params:{dbName:dbName},
        userConfigTime:true,
        success:function(response , options , opts) {
            Ext.getBody().unmask();
            var json = jsonDecode(response.responseText);
            if(json.success) {
                var id = opts.params['id'];
                if(id) {
                    downLoadFileByURL("/mysql/data/export/downLoadAllFile.do?id=" + id  + "&token=" + getUserToken());
                }
            }else {
                $.message.error(json.root);
            }
        },
        failure:function (response, options) {
            Ext.getBody().unmask();
            $.message.error(content['nowLog']);
        },
        runningCallBack:function(json , options , opts) {
            var content = json.root;
            Ext.getBody().unmask();
            if(typeof content == 'string' || typeof content == 'number') {
                opts.params['id'] = content;
                Ext.getBody().mask(message.mask.background);
                return true;
            }else {
                var status =  content['exportStatus'];
                if(status == 'END') {
                    return false;
                }
                if(status == 'ERROR') {
                    $.message.error(content['nowLog']);
                    return false;
                }
                opts.sleepTime = 2000;
                Ext.getBody().mask(message.mask.exportedTable + "：" + Ext.util.Format.htmlDecode(content['exportedTabs']) + "/" + Ext.util.Format.htmlDecode(content['exportTabNum']) + " " + (content['nowLog'] || ''));
                return true;
            }
        }
    });
};
var dropTables = function(dbName , likeTableName) {
    var store = new Ext.data.Store({
        fields:['id' , 'text'],
        proxy: {
            url:rootUrl + '/websql/getAllDbTables?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal,
            type: 'ajax',
            reader: {
                root: 'root',
                idProperty:'id'
            }
        }
    });
    store.load({params:{dbName:dbName,likeTableName:likeTableName}});
    var grid = new Ext.grid.Panel({
        selType:'checkboxmodel',
        multiSelect:true,
        columns:[
            {text: left.table.name,  dataIndex: 'text' ,sortable:false ,flex:1}
        ],
        store:store
    });
    var reloadTables = function() {
        var likeTableName = Ext.getCmp('like_table_name_2').getValue();
        store.load({params:{dbName:dbName,likeTableName:likeTableName}});
    };
    var win = new IDB.Window({
        title: left.table.dropChoose + '：' + dbName,layout:'fit',closable:true,width:630,height:430,
        items:[grid],
        tbar:[left.table.name,{
            xtype:'textfield',
            id:'like_table_name_2',
            width:350,
            value:likeTableName,
            listeners:{
                specialkey:function(field,e) {
                    if(e.getKey() == e.ENTER) {
                        reloadTables();
                    }
                }
            }
        },{
            iconCls:'fa fa-refresh',handler:reloadTables
        }],
        buttons:[{
            text: message.button.yes, handler:function() {
                var selectionRows = grid.getSelectionModel().getSelection();
                if(!selectionRows || selectionRows.length == 0) {
                    return $.message.warning(left.table.dropNone);
                }
                var selectRowArray = [];
                Ext.each(selectionRows , function(row) {
                    selectRowArray.push(row.get('text'));
                });
                dropTableDoing(selectRowArray,dbName,Ext.getCmp('like_table_name_2').getValue());
                win.close();
            }
        },{
            text: message.button.no, handler:function() {win.close()}
        }]
    });
};
var dropTableDoing = function(selectRowArray,dbName , likeTableName) {
    var dataArray = [];
    Ext.each(selectRowArray , function(table) {
        var sql = 'drop table ' + dbName + "." + table +';';
        dataArray.push({tableName:table,sql:sql,status:'wait'});
    });
    var store = new Ext.data.Store({
        fields:['tableName' , 'sql' , 'status'],
        data:dataArray
    });
    var grid = new Ext.grid.Panel({
        store:store,
        sortableColumns:false,
        deferRowRender:false,
        viewConfig:{ stripeRows:true, enableTextSelection:true},
        columns:[
            Ext.create('Ext.grid.RowNumberer', {width:30}),
            {text: left.table.operation.dropTable.title, dataIndex:"tableName", width:140},
            {text: script.executeSQL, dataIndex:"sql", width:500},
            {text: script.status, dataIndex:"status", width:70,renderer:function(v){
                if(v == 'wait') {
                    return '<img src="../img/icon/start.png" height="14"/></img>';
                }
                if(v == 'run') {
                    return '<img src="../img/icon/run.png" height="14"/></img>';
                }
                if(v == 'success') {
                    return '<img src="../img/icon/accept.png" height="14"/></img>';
                }
                if(v == 'error') {
                    return '<img src="../img/icon/error.png" height="14"/></img>';
                }
            }}
        ]
    });
    var dropBefore = function() {
        var records = [];
        store.each(function(record) {
            if(record.get('status') != 'success') {
                records.push(record);
            }
        });
        dropDoing(0 , records);
    };
    var dropDoing = function(i,records) {
    	var content = "";
        for(var j=0;j<records.length;j++){
        	content += records[j].get("sql")+"\r\n";
        }
        if(content){
        	onlyExecuteSQL(content, '', dbName, records[i].get('tableName'), 'table','',records);
        	return;
        }else{
        	$.message.error(left.table.title + '：' + records[i].get('tableName') + left.table.dropError + "：" + '参数内容为空，请选择要删除的表');
        	return;
        }
        
        //以下内容 不适于 gome生产环境 使用，测试环境可以 另行修改。 @若水.POWERMAN
        var count = records.length;
        var record = records[i];
        i++;
        if(record.get("status") == 'success') {
            if(i < count) {
                dropDoing(i , records);
            }
            return;
        }
        record.set('status' , 'run');
        win.getEl().mask(script.executingSQL + '：' + record.get('sql'));
        ajax({
            url: '/structure/table/dropTableByMainPanel.do',
            params: {script: record.get('sql'), dbName: dbName},
            success: function (resp) {
                win.getEl().unmask();
                var json = jsonDecode(resp.responseText);
                if (json.success) {
                    record.set('status' , 'success');
                    if(i < count) {
                        dropDoing(i , records);
                    }else {
                        resetInfo();
                    }
                } else {
                    record.set('status' , 'error');
                    if(i < count) {
                        Ext.Msg.confirm(message.info, left.table.title + '：' + record.get('tableName') + left.table.dropError + "：" + json.root + "," + left.table.continueDrop + "?" , function(v) {
                            if(v == 'yes') {
                                dropDoing(i , records);
                            }else {
                                resetInfo();
                            }
                        });
                    }else {
                        resetInfo();
                        return $.message.warning(left.table.title + '：' + record.get('tableName') + left.table.dropError + "：" + json.root);
                    }
                }
            },
            failure: function (resp) {
                win.getEl().unmask();
                record.set('status' , 'error');
                if(i < count) {
                    Ext.Msg.confirm(message.info, left.table.title + '：' + record.get('tableName') + left.table.dropError + "：" + json.root + "," + left.table.continueDrop + "?" , function(v) {
                        if(v == 'yes') {
                            dropDoing(i , records);
                        }else {
                            resetInfo();
                        }
                    });
                }
            }
        });
    };
    var resetInfo = function() {
        var notExecuteSQL = false;
        store.each(function(record) {
           if(!notExecuteSQL && record.get('status') != 'success') {
               notExecuteSQL = true;
           }
        });
        if(notExecuteSQL) {
            Ext.getCmp('execute_drop_table_btn').setText(left.table.proceed);
        }else {
            Ext.getCmp('execute_drop_table_btn').hide();
            Ext.getCmp('recheck_drop_table_btn').setText(left.table.proceedSelect);
        }
    };
    var win = new IDB.Window({
        title: left.table.dropConfirm + '：' + selectRowArray.length,
        width:760,height:430,maximizable:true,closable:true,items:[grid],
        buttons:[{
            text: left.table.begin, id:'execute_drop_table_btn',handler:dropBefore
        },{
            text: message.button.close, handler:function() {win.close()}
        },{
            text: left.table.reSelect, id:'recheck_drop_table_btn',handler:function() {
                dropTables(dbName , likeTableName);
                win.close();
            }
        }]
    });
    win.on('beforedestroy' , function() {
        object_panel.refreshTabPanel();
    });
};
var showTableTemplateSQL = function (prop,baseType) {
    var columns = prop['columns'] , tableName = prop['tableName'], dbName = prop['dbName'];
    var content = "/*------- INSERT SQL---------*/\n" +
        getInsertSQLByColumns(tableName, columns,baseType,dbName) +
        "/*------- UPDATE SQL---------*/\n" +
        getUpdateSQLByColumns(tableName, columns,baseType,dbName) +
        "/*------- SELECT SQL---------*/\n" +
        getSelectSQLByColumns(tableName, columns,baseType,dbName) +
        "/*------- CREATE SQL---------*/\n" +
        prop['createScript'];
    var sqlArea = new Ext.ux.form.field.CodeMirror({value: content, autoScroll: true});
    var win = new IDB.Window({
        title: left.table.title + '：[' + prop['tableName'] + "] " + left.table.information,
        width: 600, height: 340,
        items: [sqlArea],
        buttons: [
            {text: message.button.close, handler: function () {
                win.close();
            }}
        ]
    });
};
var getInsertSQLByColumns = function (tableName, columns,baseType,dbName) {
	if(baseType == 'oracle' || baseType == 'drds'){
		var start = "insert into " +dbName+'.'+ tableName + " (";
	    var values = '\n values(';
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            start += row['columnName'] + ",";
	            values += '<' + row['columnName'] + ">,";
	        });
	        start = start.substring(0, start.length - 1) + ")";
	        values = values.substring(0, values.length - 1) + ");\n\n";
	    }
	    return start + values;
	}else{
		var start = "insert into `" + tableName.replaceAll("`", "``") + "` (";
	    var values = '\n values(';
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            start += "`" + row['columnName'].replace("`", "``") + "`,";
	            values += '<' + row['columnName'] + ">,";
	        });
	        start = start.substring(0, start.length - 1) + ")";
	        values = values.substring(0, values.length - 1) + ");\n\n";
	    }
	    return start + values;
	}
};
var getUpdateSQLByColumns = function (tableName, columns,baseType,dbName) {
	if(baseType == 'oracle' || baseType == 'drds'){
		var sql = "update " +dbName+'.'+tableName + " SET ";
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            sql += "\n    " + row['columnName'] + "=<value>,";
	        });
	        sql = sql.substring(0, sql.length - 1) + "\n  where xxx = xxx;\n\n";
	    }
	    return sql;
	}else{
		var sql = "update `" + tableName.replaceAll("`", "``") + " SET ";
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            sql += "\n    `" + row['columnName'].replace("`", "``") + "`=<value>,";
	        });
	        sql = sql.substring(0, sql.length - 1) + "\n  where xxx = xxx;\n\n";
	    }
	    return sql;
	}
};
var getSelectSQLByColumns = function (tableName, columns,baseType,dbName) {
	if(baseType == 'oracle' || baseType == 'drds'){
		var sql = "select ";
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            sql += "\n    " + row['columnName'] + ",";
	        });
	        sql = sql.substring(0, sql.length - 1) + "\n  from " +dbName+'.'+ tableName + "\n  where xxx = xxx;\n\n";
	    }
	    return sql;
	}else{
		var sql = "select ";
	    if (columns && columns.length > 0) {
	        Ext.each(columns, function (row) {
	            sql += "\n    `" + row['columnName'].replace("`", "``") + "`,";
	        });
	        sql = sql.substring(0, sql.length - 1) + "\n  from `" + tableName.replaceAll("`", "``") + "`\n  where xxx = xxx;\n\n";
	    }
	    return sql;
	}
};
var showTableObject = function (prop) {
    var innoDBTitle = "";
    if(prop['engine'] == 'InnoDB') {
        innoDBTitle = " " + tableObject.estimate;
    }
    var array = [
        {data: tableObject.array.database, label: prop['dbName']},
        {data: tableObject.array.tableName, label: prop['tableName']},
        {data: tableObject.array.rows, label: prop['rows'] + innoDBTitle},
        {data: tableObject.array.dataCapacity, label: renderSize(prop['dataLength'])},
        {data: tableObject.array.indexCapacity, label: renderSize(prop['indexLength'])},
        {data: tableObject.array.comment, label: prop['comment']},
        {data: tableObject.array.engine, label: prop['engine']},
        {data: tableObject.array.charset, label: prop['charset']},
        {data: tableObject.array.collate, label: prop['collate']},
        {data: tableObject.array.autoIncrement, label: prop['autoIncrement']},
        {data: tableObject.array.rowFormat, label: prop['rowFormat']},
        {data: tableObject.array.option, label: prop['createOption']},
        {data: tableObject.array.partition, label: (prop['partitionContent'] ? tableObject.array.yes : tableObject.array.no)}
    ];
    var grid = new Ext.grid.Panel({
        selType: 'rowmodel',
        title: tableObject.property.title,
        viewConfig: { stripeRows: true, enableTextSelection: true},
        columns: [
            {xtype: 'rownumberer'},
            {text: tableObject.property.name, dataIndex: 'data', sortable: false, flex: 1},
            {text: tableObject.property.value, dataIndex: 'label', sortable: false, flex: 2}
        ],
        store: new Ext.data.Store({
            fields: ['data' , 'label'],
            data: array,
            proxy: {
                type: 'memory'
            }
        })
    });
    var sqlArea = new Ext.ux.form.field.CodeMirror({value: prop['createScript'], readOnly: true, autoScroll: true});
    var tabPanel = new Ext.tab.Panel({
        margin: '2 0 0 0', activeTab: 0, items: [grid, {
            title: tableObject.create.title, autoScroll: true,
            layout: 'fit', items: [sqlArea]
        }]
    });
    var win = new IDB.Window({
        title: left.table.title + '：[' + prop['tableName'] + "] " + left.table.information,
        width: 600, height: 340,
        items: [tabPanel],
        buttons: [
            {text: message.button.close, handler: function () {
                win.close();
            }}
        ]
    });
};

var dropFuncProc = function (treeStore, rec) {
    var parentid = rec.parentNode.get("id");
    if (parentid === left.program.trigger) {
        var trgid = rec.get("text");
        var script = 'drop trigger '+trgid;
        Ext.MessageBox.confirm(message.confirm, left.program.confirmDrop + left.program.trigger + '：' + trgid, function (btn) {
            if (btn == 'yes') {
                ajax({
                    url: getRoot()+'/dataManage/executeScript',
                    params: {dbName: treeStore.dbName, script: script,databaseId:dataBase_id,datasourceId:dataSource_id,dataSource:data_source,baseType:now_db_type,auserEmail:'test@gomeplus.com',isLocal:isLocal,sqlType:'A SQL',sqlUsage:'删除',projectName:projectListArray[0]},
                    success: function (response) {
                        var json = jsonDecode(response.responseText);
                        if (json.success) {
                            $.message.success(left.program.trigger + '：[' + trgid + '] ' + left.program.dropSuccess + '。');
                            setTimeout(function() {
                                object_panel.refreshone(objectTypeMap.progobjs);
                                console_panel.closeByObject(treeStore.dbName, trgid, 'trigger');
                            } , 50);
                        }
                    }
                });
            }
        });
    }else if (parentid === left.program.event) {
        var eventName = rec.get("text");
        var script = 'drop event '+eventName;
        Ext.MessageBox.confirm(message.confirm, left.program.confirmDrop + left.program.event + '：' + eventName, function (btn) {
            if (btn == 'yes') {
                ajax({
                    url: getRoot()+'/dataManage/executeScript',
                    params: {dbName: treeStore.dbName, script: script,databaseId:dataBase_id,datasourceId:dataSource_id,dataSource:data_source,baseType:now_db_type,auserEmail:'test@gomeplus.com',isLocal:isLocal,sqlType:'A SQL',sqlUsage:'删除',projectName:projectListArray[0]},
                    success: function (response) {
                        var json = jsonDecode(response.responseText);
                        if (json) {
                            $.message.success(left.program.event + '：[' + eventName + '] ' + left.program.dropSuccess + '。');
                            setTimeout(function() {
                                object_panel.refreshone(objectTypeMap.progobjs);
                                console_panel.closeByObject(treeStore.dbName, eventName, 'event');
                            } , 50);
                        }
                    }
                });
            }
        });
    }else if ((parentid === left.program.func) || (parentid === left.program.procedure)) {
        var objid = rec.get("text");
        var typekey = '';
        var backendtype = '';
        var script = '';
        if (parentid === left.program.func) {
            typekey = 'func';
            backendtype = 'FUNCTION';
            script = 'drop function '+objid;
        }
        else {
            typekey = 'proc';
            backendtype = 'PROCEDURE';
            script = 'drop procedure '+objid;
        }
        var prompttype = objectDisplayTypeMap[typekey];
        Ext.MessageBox.confirm(message.confirm, left.program.confirmDrop + prompttype + '：' + treeStore.dbName + "." + objid, function (btn) {
            if (btn == 'yes') {
                ajax({
                    url: getRoot()+'/dataManage/executeScript',
                    params: {funcprocType: backendtype, dbName: treeStore.dbName, script: script,databaseId:dataBase_id,datasourceId:dataSource_id,dataSource:data_source,baseType:now_db_type,auserEmail:'test@gomeplus.com',isLocal:isLocal,sqlType:'A SQL',sqlUsage:'删除',projectName:projectListArray[0]},
                    success: function (response) {
                        var json = jsonDecode(response.responseText);
                        if (json.success) {
                            $.message.success(treeStore.dbName + "." + objid + ' ' + left.program.dropSuccess + '。');
                            setTimeout(function() {
                                object_panel.refreshone(objectTypeMap.progobjs);
                                console_panel.closeByObject(treeStore.dbName, objid, typekey);
                            } , 50);
                        }
                    }
                });
            }
        });
    }
};

var createProgObjPanel = function (nowDbName) {
    var treeStore = Ext.create('Ext.data.TreeStore', {
            dbName: nowDbName,
            proxy: {
                type: 'ajax',
                url: getRoot()+'/dataManage/showProgramObjects?dbType='+now_db_type+'&dataBaseId='+dataBase_id+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal
            },
            listeners: {
                beforeload: function (store, operation, opts) {
                    if (operation.params && !operation.params.panelKey) {
                        operation.params.panelKey = getPaneKey();
                    } else {
                        operation.params = {panelKey: getPaneKey()};
                    }
                    if (!operation.params.dbName && store.dbName) {
                        operation.params.dbName = store.dbName;
                    }
                }
            }
        }
    );
    treeStore.on('load', function () {
        tree.setLoading(false);
    });

    treeStore.load();

    var showProcFuncView = function (record, action) {
        var tmpName = record.parentNode.get("id");
        switch(tmpName) {
            case left.program.trigger: console_panel.addUrlPanel(rootUrl+'/dataManage/trigger/createTrigger', record.get('text'), 'trigger', action,null,null,null,'TRIGGER');break;
            case left.program.func: console_panel.addUrlPanel(rootUrl+'/dataManage/function/function-page', record.get('text'), 'func', action,null,null,null,'FUNCTION');break;
            case left.program.procedure: console_panel.addUrlPanel(rootUrl+'/dataManage/getProcedurePage', record.get('text'), 'proc', action,null,null,null,'PROCEDURE');break;
            case left.program.event: console_panel.addUrlPanel('/structure/event/getEventDetail.do', record.get('text'), 'event', action);break;
        }
    };
    
    var executeProcedure = function (record, action) {
        var tmpName = record.parentNode.get("id");
        var result = console_panel.addUrlPanel(rootUrl+'/dataManage/getProcedurePage', record.get('text'), 'proc', action,null,null,null,'PROCEDURE');
        if (result && result.old) {
            var iframe = document.getElementById(result.old + "_iframe");
            if(!iframe.contentWindow.action_fun.isExecute) {
                iframe.contentWindow.action_fun.executeProcedure();
            }else {
                $.message.warning('该存储过程正在执行中....');
            }
        }
    };

    var executeFunction = function (record, action) {
        var tmpName = record.parentNode.get("id");
        var result = console_panel.addUrlPanel(rootUrl+'/dataManage/function/function-page', record.get('text'), 'func', action,null,null,null,'FUNCTION');
        if (result && result.old) {
            var iframe = document.getElementById(result.old + "_iframe");
            if(!iframe.contentWindow.action_fun.isExecute) {
                iframe.contentWindow.action_fun.executeFunction();
            }else {
                $.message.warning('该函数正在执行中....');
            }

        }
    };

    /**
     * 树类的代码
     * @type {Ext.tree.Panel}
     */
    var tree = new Ext.tree.Panel({
        store: treeStore,
        title: left.program.title,
        rootVisible: false,
        name: 'funcProcTrees',
        refreshByDBName: function (dbName) {
            treeStore.dbName = dbName;
            tree.setLoading(true);
            treeStore.load();
        },
        listeners: {
            itemcontextmenu: function (view, rec, node, index, e) {
                e.stopEvent();
                showMenu(rec , e);
            },
            itemclick: function (thiz, record , item, index, e) {
                showMenu(record , e);
            }
        }
    });

    var showMenu = function(rec , e) {
        var leaf = rec.get("leaf");
        var tmpName = null;
        var newCallBack = function() {
            switch(tmpName) {
                case left.program.trigger: console_panel.addUrlPanel(rootUrl+'/dataManage/trigger/createTrigger', '', 'trigger', 'create',null,null,null,'TRIGGER');break;
                case left.program.func: console_panel.addUrlPanel(rootUrl+'/dataManage/function/function-page', '', 'func', 'create',null,null,null,'FUNCTION');break;
                case left.program.procedure: console_panel.addUrlPanel(rootUrl+'/dataManage/getProcedurePage', '', 'proc', 'create',null,null,null,'PROCEDURE');break;
                case left.program.event: console_panel.addUrlPanel(rootUrl+'/dataManage/event/createEvent', '', 'event', 'create',null,null,null,'EVENT');break;
            }
        };
        var displayName, rightMenu;
        if (!leaf) {
            var itemId = tmpName = rec.get("id");
            displayName = "（" + itemId + "）";
            rightMenu = Ext.create('Ext.menu.Menu', {
                width: 60,
                plain: true,
                floating: true,
                items: [
                    {
                        text: menu.New + displayName,
                        handler: newCallBack
                    },
                    {
                        text: menu.refresh,
                        handler: function () {
                            object_panel.refreshone(objectTypeMap.progobjs);
                        }
                    }
                ]
            });
            rightMenu.showAt(e.getXY());
        }else {
            var parentId = tmpName = rec.parentNode.get("id");
            displayName = "（" + parentId + "）";
            rightMenu = Ext.create('Ext.menu.Menu', {
                width: 140,
                plain: true,
                floating: true,
                items: [
                    {
                        text: menu.New + displayName,
                        handler: newCallBack
                    },
                    {
                        text: menu.edit + displayName,
                        handler: function () {
                            showProcFuncView(rec, 'edit');
                        }
                    },
                    {
                        text: menu.drop + displayName,
                        handler: function () {
                            dropFuncProc(treeStore, rec);
                        }
                    }
                ]
            });
//            if(parentId == left.program.procedure) {
//                rightMenu.insert(3 , {
//                    text: menu.execute + displayName,
//                    handler:function () {
//                        executeProcedure(rec, 'executeProcedure');
//                    }
//                });
//            }else if(parentId == left.program.func) {
//                rightMenu.insert(3 , {
//                    text: menu.execute + displayName,
//                    handler:function () {
//                        executeFunction(rec, 'executeFunction');
//                    }
//                });
//            }

            /*if(parentId == left.program.procedure || parentId == left.program.func) {
                rightMenu = Ext.create('Ext.menu.Menu', {
                    width: 140,
                    plain: true,
                    floating: true,
                    items: [
                        {
                            text: menu.New + displayName,
                            handler: newCallBack
                        },
                        {
                            text: menu.edit + displayName,
                            handler: function () {
                                showProcFuncView(rec, 'edit');
                            }
                        },
                        {
                            text: menu.drop + displayName,
                            handler: function () {
                                dropFuncProc(treeStore, rec);
                            }
                        },{
                            text: menu.execute + displayName,
                            handler:function () {
                                executeProcedure(rec, 'executeProcedure');
                            }
                        }
                    ]
                });
            }*/

            rightMenu.showAt(e.getXY());
        }
    }
    return tree;
};


/**
 * 左侧树图的视图类
 * @type {Array}
 */
var PUBLIC_RIGHT_MENUS = [];
var createViewPanel = function (nowDbName) {
    var treeStore = new IDB.TreeStore({
        autoLoad: false,
        dbName: nowDbName,
        root: {text: left.view.list, expanded: true},
        url: rootUrl + '/dataManage/view/showViews?dataBaseId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal
    });
    treeStore.on('load', function() {
        tree.setLoading(false);
    });
    var tmpRecord = null;
    var rightMenu = new Ext.menu.Menu({
        items: [
            {
                text: left.view.check, handler: function () {
                    if (tmpRecord) {
                        console_panel.addUrlPanel(rootUrl + '/websql/gmwebsql/multiSqlWindow', tmpRecord.get('text'), 'sqlWindow', 'query' , null,getSQLWindowParamsStr("sqlWindow" , ""));
                    }
                }
            },
            {
                text: left.view.New, handler: function () {
                    console_panel.addUrlPanel(rootUrl + '/dataManage/view/createViewBase', '', 'view', 'create');
                }
            },
            {
                text: left.view.edit, handler: function () {
                if (tmpRecord) {
                    console_panel.addUrlPanel(rootUrl+'/dataManage/view/createViewBase', tmpRecord.get('text'), 'view', 'change');
                }
            }
            },
            {
                text: left.view.drop, handler: function () {
                if (tmpRecord) {
                    Ext.Msg.confirm(message.warning, left.view.dropConfirm + '?', function (v) {
                        if (v == 'yes') {
                            onlyExecuteSQL('drop view `' + String(tmpRecord.get('text')).replaceAll("`", "``") + "`", tree, tmpName, tmpRecord.get('text'), 'view','view');
                        }
                    });
                }
            }
            },
            {
                text: menu.refresh, handler: function () {
                    tree.refreshByDBName(tmpName);
                }
            }
        ]
    });
    var rightMenu2 = new Ext.menu.Menu({
        items: [
            {
                text: left.view.New, handler: function () {
                    console_panel.addUrlPanel(rootUrl+'/dataManage/view/createViewBase', '', 'view', 'create');
                }
            },
            {
                text: menu.refresh, handler: function () {
                    tree.refreshByDBName(tmpName);
                }
            }
        ]
    });
    PUBLIC_RIGHT_MENUS.push(rightMenu, rightMenu2);
    var tmpName = nowDbName;
    var tree = new Ext.tree.Panel({
        store: treeStore,
        title: left.view.title,
        rootVisible: false,
        refreshByDBName: function (dbName) {
            tmpName = treeStore.dbName = dbName;
            tree.setLoading(true);
            treeStore.load();
        },
        listeners: {
            itemclick: function (thiz, record, item, index, e) {
                tmpRecord = record;
                rightMenu.showAt(e.getXY());
            },
            itemcontextmenu: function (thiz, record, item, index, e) {
                e.preventDefault();
                tmpRecord = record;
                rightMenu.showAt(e.getXY());
            },
            containercontextmenu: function (thiz, e) {
                e.preventDefault();
                rightMenu2.showAt(e.getXY());
            }
        }
    });
    return tree;
};
var console_function = {
    appendObjectInfoForId: function (url, name, objectType, panelKey, operation, nowDBName, preId, params) {
        if (url.indexOf("?") == -1) {
            url += '?'
        } else {
            url += '&';
        }
        if (url_namespace) {url = "/" + url_namespace + url;}
        return url + 'objectName=' + (name ? encodeURIComponent(name) : '')
            + "&objectType=" + objectType
            + "&panelKey=" + panelKey
            + '&operation=' + operation
            + "&nowDBName=" + (nowDBName ? encodeURIComponent(nowDBName) : '')
            + "&tabId=" + (preId ? encodeURIComponent(preId) : '')
            + '&params=' + encodeURIComponent(params || '')
            + '&dbVersionNum=' + encodeURIComponent(db_version_num);
    }
};
var refreshTabCallBack = function (tabId, objectName, objectType, nowDBName, panelKey) {
    console_panel.changeUrlPanel('/structure/table/tableBase.do', objectName, objectType, 'change', tabId, panelKey, nowDBName);
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshTabPanel();
    }
};
var refreshFunctionCallBack = function (tabId, objectName, objectType, nowDBName, panelKey) {
    console_panel.changeUrlPanel(rootUrl+'/dataManage/function/function-page', objectName, objectType, 'change', tabId, panelKey, nowDBName,'FUNCTION');
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshTabPanel();
    }
};
var refreshProcedureCallBack = function (tabId, objectName, objectType, nowDBName, panelKey) {
    console_panel.changeUrlPanel(rootUrl+'/dataManage/getProcedurePage', objectName, objectType, 'change', tabId, panelKey, nowDBName,'PROCEDURE');
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshTabPanel();
    }
};
var closeTabCallBack = function (tabId, nowDBName) {
    console_panel.closeTab(tabId);
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshTabPanel();
    }
};
var closeViewCallBack = function (tabId, nowDBName) {
    console_panel.closeTab(tabId);
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshViewPanel();
    }
};
var refreshViewCallBack = function (tabId, objectName, objectType, nowDBName, panelKey) {
    console_panel.changeUrlPanel(rootUrl +'/dataManage/view/createViewBase', objectName, objectType, 'change', tabId, panelKey, nowDBName);
    if (object_panel.getNowDBName() == nowDBName) {
        object_panel.refreshViewPanel();
    }
};
var queryObjectCallBack = function (nowDBName, objectName) {
    console_panel.addUrlPanel(rootUrl+'/dataManage/queryTable', objectName, 'query_table', 'query_table' , nowDBName);
};
var getJSONValue = function (json, key) {
    return json[key] || '';
};
var welcomePanel = function () {
	var url='';
	if(isLocal=='isLocal'){
		url=getRoot()+'/websql/gmwebsql/welcome?dataBaseId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal=isLocal';
	}else{
		url=getRoot()+'/websql/gmwebsql/welcome?dataBaseId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'';
	}
	
    return new Ext.Panel({
        id:'welcome_panel_id',
        title: homePage,
        html:getFrameHtmlWithId(url, "welcome_page_id")
    });
};
var sql_window_sqls_keys = [];
var init_default_active_tab = null;
var getSQLWindowParamsStr = function(objectType , sql , oldParams) {
    if(objectType == 'sqlWindow') {
       /* var tmpKey = "__dms_store_" + getUserToken() + "_" + uuid();*/
    	var tmpKey = "__dms_store_" + 11 + "_" + uuid();
        sql_window_sqls_keys.push(tmpKey);
        SimpleStorageUtils.set(tmpKey , sql);
        var params = oldParams || {};
        params['temp_store_sql_key'] = tmpKey;
        return jsonToString(params);
    }
    return "";
};
var init_active_preId = null;
var initTabs = function(index) {
    var tabArray = init_store_tabs['tabArray'] || [];
    if(tabArray.length <= index) {
        if(init_active_preId) {
            setTimeout(function() {
                console_panel.activeId(init_active_preId);
            } , 100);
        }
        return;
    }

    var row = tabArray[index];
    var params = getSQLWindowParamsStr(row.objectType , row.sql , jsonDecode(row.params , {}));

    var object = console_panel.addUrlPanel(
        row.url,
        row.objectName,
        row.objectType,
        row.operation,
        row.nowDBName,
        params,
        true
    );
    if(row.activeTab === "true") {
        init_active_preId = object.preId;
    }

    setTimeout(function() {
        initTabs(index + 1);
    } , 80);
};
var storeTabs = function() {
    var active = console_panel.getActiveTab().id;
    var object = {dbName : object_panel.getNowDBName()};
    var tabArray = [];
    for(var p in  remember_tabs) {
        var row = remember_tabs[p];
        var preId = row['preId'];
        var objectType = row.objectType;
        var tab = remember_tabs[p];
        if(objectType == 'sqlWindow') {
            var panel = Ext.getCmp(preId);
            if(!panel.preHtmlCode) {
                var iframeId = preId + "_iframe";
                var iframe = document.getElementById(iframeId);

                tab.nowDBName = iframe.contentWindow.nowDBName;
                tab.sql = iframe.contentWindow.getFullSqlText();
            }else {
                tab.sql = SimpleStorageUtils.get(tab['tmpKey']);
            }

            if(row.operation != 'add') {
                delete tab['objectName'];
            }
        }
        if(active == preId) {
            tab.activeTab = "true";
        }
        tabArray.push(tab);
    }
    object.tabArray = tabArray;
    SimpleStorageUtils.set("__DMS_INSTANCE_" + connect_ip + ":" + connect_port + "@" + connect_user, jsonToString(object));
    sql_window_sqls_keys.each(function(row) {
        SimpleStorageUtils.remove(row);
    });
};
var remember_tabs = {};
var rememberTab = function(preId,property) {
    if(isRememberTab(property['objectType'] , property['operation'])) {
        property['preId'] = preId;
        remember_tabs["preId_" + preId] = property;
    }
};
var deleteRememberTab = function(preId) {
    var key = "preId_" + preId;
    if(remember_tabs[key]) {
        delete remember_tabs[key];
    }
};
var isRememberTab = function(objectType , operation) {
    if(operation == 'add' && objectType == 'sqlWindow') {
        return true;
    }
    return operation == 'manage_erchart' ||
        operation == 'query' || operation == 'query_table' ||
        objectType == 'orzdba' || objectType == 'showprocesslist' || objectType == 'tablesummary' || objectType == 'diagnosis';
};
var createWorkspaceCenterPanel = function () {
    var tmpNum = 1;
    var newOldKV = {} , oldNewKV = {} , tabs = 0;
    var tabPanel = new Ext.tab.Panel({
        id:"tobeNormal",
        margin:"5 0 0 5",
        activeTab: 0,
        minTabWidth: 90,
        maxTabWidth: 160,
        collapsible: false,
        region: 'center',
        bodyStyle: "border-top:1px solid #ddd;z-index: 8;border-left:1px solid #ddd;",
        items: [
            welcomePanel()
        ],
        addTmpURLPanel: function (url, title, objectType) {
            var params = null;
            tabPanel.addUrlPanel(url, title, objectType, 'add' , null , getSQLWindowParamsStr(objectType , ""));
        },
        closeTab: function (oldPreId) {
            var remote = Ext.getCmp(oldPreId);
            if (remote) {
                tabPanel.remove(remote);
            }
        },
        closeByObject: function (dbName, objectName, objectType) {
            var preId = TabUtil.calculateExistingObjPreId(dbName, objectName, objectType);
            var remote = Ext.getCmp(preId);
            if (remote) {
                tabPanel.remove(remote);
            }
            if (newOldKV[preId]) {
                remote = Ext.getCmp(newOldKV[preId]);
                if (remote) {
                    tabPanel.remove(remote);
                }
            }
        },
        saveOldNewPanelIdMap: function (oldPreId, newpreid) {
            var oldRelative = oldNewKV[oldPreId];
            if (oldRelative) {
                newOldKV[oldRelative] = null;
            }
            newOldKV[newpreid] = oldPreId;
            oldNewKV[oldPreId] = newpreid;
        },

        resetTabTitle:function(preId,newTitle) {
            var remote = Ext.getCmp(preId);
            if (remote && tabPanel.getEl(remote)) {
                remote.setTitle(newTitle);
            }
        },
        changeUrlPanel: function (url, objectName, objectType, operation, oldPreId, panelId, nowDBName) {
            var preId , title;
            preId = nowDBName + "_" + objectName + "_" + objectType;
            title = (objectType == 'table' || objectType == 'func' || objectType == 'proc' ? menu.edit : '') + getObjectCNameByEName(objectType) + ':' + objectName;
            var remote = Ext.getCmp(oldPreId);
            if (remote && tabPanel.getEl(remote)) {
                if (oldPreId != preId) {
                    var oldRelative = oldNewKV[oldPreId];
                    if (oldRelative) {
                        newOldKV[oldRelative] = null;
                    }
                    newOldKV[preId] = oldPreId;
                    oldNewKV[oldPreId] = preId;
                }
                remote.setTitle(title);
                Ext.get(oldPreId + "_iframe").dom.src = console_function.appendObjectInfoForId(url, objectName, objectType, panelId, operation, nowDBName, oldPreId);
            }
        },
        closeNotSQLPanel:function() {
            var items = tabPanel.items.items;
            var removeItem = [];
            Ext.each(items , function(row) {
                if(row && row.id) {
                    var id = row.id;
                    if(id != 'welcome_panel_id') {
                        if(id.indexOf("query") == -1 && id.indexOf("sqlWindow") == -1 && id.indexOf("sqlCommand") == -1) {
                            removeItem.push(row);
                        }else {
                            var iFrame = document.getElementById(id + "_iframe");
                            iFrame.contentWindow.instanceChangeCallBack();
                        }
                    }
                }
            });
            Ext.each(removeItem , function(item) {
                tabPanel.remove(item);
            });
        },
        addUrlPanel: function (url, objectName, objectType, operation, nowDBName, params , lazyLoad,funcType) {
            var preId, title;
            nowDBName = nowDBName || object_panel.getNowDBName();
            if (operation == 'add') {
                preId = 'new_' + (tmpNum++) + "_" + objectType;
                title = objectName;
            } else if (operation == 'tableBatchOptr') {
                preId = 'new_' + nowDBName;
                title = left.table.operation.batchOperation.title + '(' + nowDBName + ')';
            } else if (operation == 'query') {
                preId = 'new_' + (tmpNum++) + "_" + objectType;
                title = left.table.operation.SQLoperation.tab;
            }else if(operation == "query_table") {//打开表
                preId = 'query_table_' + "_" + nowDBName + "_" + objectName;
                title = left.table.title + '：' + objectName;
            }  else if (operation == 'create') {
                preId = 'new_' + (tmpNum++) + "_" + objectType;//新增一个窗口
                title = operationMap[operation] + "：" + getObjectCNameByEName(objectType);
            } else if (operation == 'export' || operation == 'import') {
                preId = objectName + "_" + objectType;
                title = (operation == 'export' ? menu.Export : menu['import']);
            } else if (operation == 'manage_erchart' ) {
            	preId = 'new_' + objectType;
 				title = menu.ERFigure + '：' + nowDBName;
            } else if (operation == 'instance' || operation == 'grant' || operation.substring(0 , 6) == 'manage' || operation == 'more') {
                preId = objectName + "_" + objectType;
                title = objectName;
            } else {
                preId = TabUtil.calculateExistingObjPreId(nowDBName, objectName, objectType);
                title = (objectType == 'table' ? menu.edit : '') + " " + getObjectCNameByEName(objectType) + '：' + objectName;
            }
            if (!tabPanel.containsIdPanel(preId) && !tabPanel.containsRelativeIdPanel(preId)) {
                if (tabs >= 19) {
                    return $.message.warning(message.tooManyWin);
                }
                ajax({
                    url: rootUrl+'/websql/gwebsql/ajaxNewSqlEditorPanel',
                    onlyUrl: true,
                    success: function (response) {
                    	var json = jsonDecode(response.responseText);
                        if (json.success) {
                            var panelId = json.root;
                            var iframeId = preId + "_iframe";
                            var realURL;
                            if(isLocal=='isLocal'){
                            	realURL = url + '?dataBaseId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&dbName='+nowDBName+'&objectName='+objectName+'&operation='+operation+'&objectType='+objectType+'&tabId='+(preId ? encodeURIComponent(preId) : '')+'&funcprocType='+funcType+'&params=' + encodeURIComponent(params || '') + '&isLocal=isLocal';
                            }else{
                            	realURL = url + '?dataBaseId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&dbName='+nowDBName+'&objectName='+objectName+'&operation='+operation+'&objectType='+objectType+'&tabId='+(preId ? encodeURIComponent(preId) : '')+'&funcprocType='+funcType+'&params=' + encodeURIComponent(params || '') + '';
                            }
                            var htmlCode = getFrameHtmlWithId(realURL, iframeId);
                            var remote = new Ext.Panel({
                                id: preId, panelKey: panelId, border: false, title: title, closable: true, scripts: true, autoScroll: false,
                                discardUrl: true, nocache: true, timeout: 9000, scope: this, preHtmlCode : htmlCode,
                                tabConfig:{
                                    tooltip:title
                                }
                            });
                            tabPanel.add(remote);
                            if(!lazyLoad) {
                                tabPanel.lazyLoad(remote);
                                tabPanel.setActiveTab(remote);
                            }
                            var tmpKey = null;
                            try {
                                if(params && objectType == 'sqlWindow') {
                                    var parsered_params = jsonDecode(params);
                                    if(parsered_params.temp_store_sql_key) {
                                        tmpKey = parsered_params.temp_store_sql_key;
                                    }
                                }
                            } catch(e) {}

                            rememberTab(preId,{
                                url:url,
                                objectName:objectName,
                                objectType:objectType,
                                operation:operation,
                                nowDBName:nowDBName,
                                params:params,
                                tmpKey:tmpKey
                            });
                            tabs++;
                            remote.on('beforedestroy', function () {
                                tabs--;
                                deleteRememberTab(preId);
                                var iframe = document.getElementById(iframeId);
                                if(tmpKey) {
                                    SimpleStorageUtils.remove(tmpKey);
                                }
                                try {
                                    if (Ext.isIE) {//IE浏览器内存泄露
                                        iframe.contentWindow.document.write('');
                                        iframe.contentWindow.close();
                                    }
                                }catch(e) {}

                            });
                        }
                    }
                });
                return {preId : preId};
            } else {
                if (newOldKV[preId]) {
                    tabPanel.activeId(newOldKV[preId]);
                } else {
                    tabPanel.activeId(preId);
                }
                return {old: preId};
            }
        },
        containsIdPanel: function (id) {
            var remote = Ext.getCmp(id);
            return (remote && tabPanel.getEl(remote));
        },
        containsRelativeIdPanel: function (id) {
            if (newOldKV[id]) {
                return tabPanel.containsIdPanel(newOldKV[id]);
            }
            return false;
        },
        activeId: function (id) {
            var remote = Ext.getCmp(id);
            tabPanel.setActiveTab(remote);
        },
        lazyLoad : function(card) {
            if(card.preHtmlCode != null) {
                card.html = card.preHtmlCode;
                card.preHtmlCode = null;
            }
        },
        listeners:{
            beforetabchange:function(tab , newCard , oldCard , opts) {
               tabPanel.lazyLoad(newCard);
            }
        }
    });
    return tabPanel;
};